package cn.article.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.article.dto.ConditionDto;
import cn.article.entity.ArticleInfo;
import cn.article.entity.Province;
import cn.article.error.ErrorCode;
import cn.article.service.ArticleInterface;
import cn.easier.club.base.dto.ResultInfo;
import cn.easier.club.base.utils.ExcelUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@CrossOrigin(origins = { "*" }, methods = { RequestMethod.GET, RequestMethod.POST })
public class ArticleController {

	private static Logger log = LoggerFactory.getLogger(ArticleController.class);

	@Resource
	private ArticleInterface articleInterface;
	

	/**
	 * Excel批量添加商品
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/save-articles", method = RequestMethod.POST)
	public ResultInfo saveMoreGoods(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		ResultInfo resultInfo = null;
		String contentType = file.getContentType();
		String fileName = file.getOriginalFilename();
		log.info("文件类型及名字;file contentType=>{},fileName=>{}", contentType, fileName);
		String dirPath = request.getSession().getServletContext().getRealPath("excelupload/");
		try {
			uploadFile(file.getBytes(), dirPath, fileName); // 将上传的文件写入到目标路径
			String filePath = dirPath + fileName;
			InputStream in = new FileInputStream(new File(filePath));
			log.info("this excel file path=>{}", filePath);
			Workbook wb = ExcelUtil.chooseWorkbook(fileName, in); // 判断Excel版本，选择创建Workbook的方式
			ArticleInfo articleInfo = new ArticleInfo();// 读取对象列表的信息
			List<ArticleInfo> readDateListT = ExcelUtil.readDataListT(wb, articleInfo, 2, 0);// 第一行表头，从第二行开始读取
			log.info("excel info=>{}", readDateListT);
			for (ArticleInfo articleInfos : readDateListT) {
				if (null == articleInfos.getCreateTime()) {
					articleInfos.setCreateTime(new Date());
				}
				articleInterface.saveArticle(articleInfos);
			}
			resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS",
					readDateListT.size() + "条数据添加完成");
		} catch (Exception e) {
			log.info("save articleInfo fail=>{}", e);
			e.printStackTrace();
			return new ResultInfo(ErrorCode.SAVE_EXCELL_FAIL.code, ErrorCode.SAVE_EXCELL_FAIL.info, null);
		}
		return resultInfo;
	}


	@RequestMapping(value = "/get-articles", method = RequestMethod.POST)
	public ResultInfo findAllByConditions(@RequestBody ConditionDto conditionDto) {
		log.info("接受的参数conditions", conditionDto.toString());
		List<ArticleInfo> resultList = null;
		ResultInfo resultInfo = null;
		JSONArray jsonArray = null;
		try {
			resultList = articleInterface.findAllByConditions(conditionDto);
			if(resultList!=null){
				for (ArticleInfo ar : resultList) {
					ar.setCreateTime(null);
				}
			}
			jsonArray = JSONArray.fromObject(resultList);
			resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", jsonArray.toString());
			return resultInfo;
		} catch (Exception e) {
			log.info("web,query articleInfo fail=>{}", e);
			e.printStackTrace();
			return new ResultInfo(ErrorCode.QUERY_ARTICLES_FAIL.code, ErrorCode.QUERY_ARTICLES_FAIL.info, null);
		}
	}

	/**
	 * 通过唯一的物流单号进行查询
	 * 
	 * @param articleNum
	 * @return
	 */
	@RequestMapping(value = "/get-by-articleNum", method = RequestMethod.GET)
	public ResultInfo findByArticleNum(@RequestParam("articleNum") String articleNum) {
		log.info("接受的参数articleNum=>{}", articleNum);
		ArticleInfo result = null;
		JSONObject jsonObj = null;
		ResultInfo resultInfo = null;
		try {
			result = articleInterface.findByArticleNum(articleNum);
			if(result!=null){
			result.setCreateTime(null);
			}
			jsonObj = JSONObject.fromObject(result);
			resultInfo = new ResultInfo(String.valueOf(HttpServletResponse.SC_OK), "SUCCESS", jsonObj.toString());
			return resultInfo;
		} catch (Exception e) {
			log.info("web,articleNum,query articleInfo fail=>{}", e);
			e.printStackTrace();
			return new ResultInfo(ErrorCode.GET_BY_ARTICLENUM.code, ErrorCode.GET_BY_ARTICLENUM.info, null);
		}
	}

	
	@RequestMapping(value = "/save-province", method = RequestMethod.POST)
	public ResultInfo saveProvince(@RequestBody Province province) {
		ResultInfo resultInfo=null;
		try {
		   resultInfo = articleInterface.saveProvince(province);
		   return resultInfo; 
		} catch (Exception e) {
			log.info("save province fail=>{}", e);
			e.printStackTrace();
			return new ResultInfo(ErrorCode.SAVE_PROVINCE_FAIL.code, ErrorCode.SAVE_PROVINCE_FAIL.info, null);
		}
	}
	
	@RequestMapping(value = "/get-province", method = RequestMethod.GET)
	public ResultInfo getProvinces() {
		ResultInfo resultInfo=null;
		try {
			resultInfo = articleInterface.findAll();
		    return resultInfo;
		} catch (Exception e) {
			log.info("query province fail=>{}", e);
			e.printStackTrace();
			return new ResultInfo(ErrorCode.QUERY_PROVINCE_FAIL.code, ErrorCode.QUERY_PROVINCE_FAIL.info, null);
		}
	}
	
	
	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}
}
